﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Generic;
using WebSite.Admin.Core;


namespace WebSite.Admin
{
	public partial class Admin_RiseBaby : AdminBasePage
	{
	
	// Coded by wenbin 2012-10-24 22:37:10
		#region 实体类
		/// <summary>
		/// 实体类
		/// </summary>
		private class RiseBaby
		{
			private int _id = 0;	
			public  int  Id  
			{
				get{ return  _id; }
				set{ _id = value; }
			}
			private string _babyName = string.Empty;	
			public  string  BabyName  
			{
				get{ return  _babyName; }
				set{ _babyName = value; }
			}
			private string _babyUrl = string.Empty;	
			public  string  BabyUrl  
			{
				get{ return  _babyUrl; }
				set{ _babyUrl = value; }
			}
			private string _babyImage = string.Empty;	
			public  string  BabyImage  
			{
				get{ return  _babyImage; }
				set{ _babyImage = value; }
			}
			private int _orderId = 0;	
			public  int  OrderId  
			{
				get{ return  _orderId; }
				set{ _orderId = value; }
			}
			private int _exInt = 0;	
			public  int  ExInt  
			{
				get{ return  _exInt; }
				set{ _exInt = value; }
			}
			private string _exString = string.Empty;	
			public  string  ExString  
			{
				get{ return  _exString; }
				set{ _exString = value; }
			}
	
	}
		#endregion
	
		dbHelper db = new dbHelper();
		
		/// <summary>
        /// 查询id
        /// </summary>
        public long QId
        {
            get
            {
                return Convert.ToInt64(Request.QueryString["id"]);
            }
        }
		
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			//dbHelper.CheckIsLogin();
		}
	
	
		protected void Page_Load(object sender, EventArgs e)
		{
			string redirectUrl = HttpContext.Current.Request.Url.ToString().Split('?')[0];
			int page = Convert.ToInt32(Request.QueryString["page"]);
			if (page == 0)
				page = 1;
			string urlPage = "page=" + page;
			string strWhere = " 1=1 ";
			string urlParams = "";
			string searchId= dbHelper.FilterSql(Request.QueryString["searchId"]);
			if (!string.IsNullOrEmpty(searchId))
			{
				strWhere +=" and Id ="+searchId+"";
				urlParams += "&searchId=" + searchId;
			}
			string searchBabyName= dbHelper.FilterSql(Request.QueryString["searchBabyName"]);
			if (!string.IsNullOrEmpty(searchBabyName))
			{
				strWhere +=" and BabyName like '%"+searchBabyName+"%'";
				urlParams += "&searchBabyName=" + searchBabyName;
			}
			string searchBabyUrl= dbHelper.FilterSql(Request.QueryString["searchBabyUrl"]);
			if (!string.IsNullOrEmpty(searchBabyUrl))
			{
				strWhere +=" and BabyUrl like '%"+searchBabyUrl+"%'";
				urlParams += "&searchBabyUrl=" + searchBabyUrl;
			}
			string searchBabyImage= dbHelper.FilterSql(Request.QueryString["searchBabyImage"]);
			if (!string.IsNullOrEmpty(searchBabyImage))
			{
				strWhere +=" and BabyImage like '%"+searchBabyImage+"%'";
				urlParams += "&searchBabyImage=" + searchBabyImage;
			}
			string searchOrderId= dbHelper.FilterSql(Request.QueryString["searchOrderId"]);
			if (!string.IsNullOrEmpty(searchOrderId))
			{
				strWhere +=" and OrderId ="+searchOrderId+"";
				urlParams += "&searchOrderId=" + searchOrderId;
			}
			string searchExInt= dbHelper.FilterSql(Request.QueryString["searchExInt"]);
			if (!string.IsNullOrEmpty(searchExInt))
			{
				strWhere +=" and ExInt ="+searchExInt+"";
				urlParams += "&searchExInt=" + searchExInt;
			}
			string searchExString= dbHelper.FilterSql(Request.QueryString["searchExString"]);
			if (!string.IsNullOrEmpty(searchExString))
			{
				strWhere +=" and ExString like '%"+searchExString+"%'";
				urlParams += "&searchExString=" + searchExString;
			}
			
			urlPage = urlPage + urlParams;
			if(!string.IsNullOrEmpty(urlParams))
				urlParams = urlParams.Substring(1, urlParams.Length - 1);
			redirectUrl = redirectUrl + "?" + urlPage;
			
			//数据导出
	 		string toExcel = dbHelper.FilterSql(Request.QueryString["toExcel"]);
            if (toExcel == "1")
            {
                ExcelSubmit(strWhere);
            }
	
			//分页
			Paging(page, strWhere, urlParams);
	
			//业务
			BussessOper(redirectUrl);
	
		
		}
	
	  	#region  --数据导出---
       
        /// <summary>
        /// 保存xls文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExcelSubmit(string sWhere)
        {		 	
			string sSelect = "Id as 'Id',BabyName as '宝贝名字',BabyUrl as '宝贝外链',BabyImage as '宝贝图片',OrderId as '排序值',ExInt as '扩展字段1',ExString as '扩展字段2'";
			
            string some_search = string.Format("select {0} from RiseBaby(nolock) where {1} ", sSelect, sWhere); //查询语句
            DataSet ds = db.returndataset(null, some_search, null, null);

            //填冲到XLS中////
            AdminCommon.xlsGridview(ds, string.Format("数据_{0}", DateTime.Now));
        }

        #endregion
	
	
		#region 分页
		public void Paging(int page, string strWhere, string urlParams)
		{
			dbHelper.pageproret record = new dbHelper.pageproret();
	
			record = db.GetPageRecordSet("RiseBaby", page, 20, "Id", "Id Desc", "*", strWhere);
			int pagecount = record.pagecount;
			DataTable dt = record.recordset;
			List<RiseBaby> datasrc = db.ConvertTo<RiseBaby>(dt).ToList();
				
			 DataList.DataSource = datasrc.Count > 0 ? datasrc : null;
            DataList.DataBind();
		
			string pager = db.BuildPager(page, pagecount, "", urlParams);
			sPage.Text = pager;
		}
	
		#endregion
	
		#region 业务处理
		/// <summary>
		/// 业务处理
		/// </summary>
		/// <param name="redirectUrl"></param>
		public void BussessOper(string redirectUrl)
		{
			if (Request.QueryString["act"] == "del")
			{				
				if (QId != 0)
				{
					DeleteData(QId);
					Response.Redirect(redirectUrl);
				}
			}
	
			if (Request.ServerVariables["REQUEST_METHOD"] == "POST")
			{
				string idStr = dbHelper.FilterSql(Request.Form["SelectID"]);
				if (!string.IsNullOrEmpty(idStr))
				{
					idStr = idStr.Replace(" ", "");
					idStr = idStr.Replace("&nbsp;", "");
					if (!string.IsNullOrEmpty(Request.Form["delete"]))
					{
						DeleteBatchData(idStr);
						Response.Redirect(redirectUrl);
					}
					if (!string.IsNullOrEmpty(Request.Form["pingbi"]))
					{
						SwitchBatchData(0, idStr);
						Response.Redirect(redirectUrl);
					}
					if (!string.IsNullOrEmpty(Request.Form["fabu"]))
					{
						SwitchBatchData(1, idStr);
						Response.Redirect(redirectUrl);
					}
					Response.Redirect(redirectUrl);
					Response.End();
				}
				RiseBaby sdata = new RiseBaby();
				
				//string modid = Request.Form["ModId"] == null ? "0" : Request.Form["ModId"].Trim();
				//int id =sdata.Id = Convert.ToInt32(modid);
					sdata.Id  = Convert.ToInt32(dbHelper.FilterSql(Request.Form["ModId"].Trim())?? "");
					sdata.BabyName  = Convert.ToString(dbHelper.FilterSql(Request.Form["ModBabyName"].Trim())?? "");
					sdata.BabyUrl  = Convert.ToString(dbHelper.FilterSql(Request.Form["ModBabyUrl"].Trim())?? "");
					sdata.BabyImage  = Convert.ToString(dbHelper.FilterSql(Request.Form["ModBabyImage"].Trim())?? "");
                    
                //上传图片
                    string fileImageBig = string.Empty;
                    if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                    {
                        try
                        {
                            System.Drawing.Image img = System.Drawing.Image.FromStream(Request.Files[0].InputStream);
                            if (Request.Files[0].ContentLength > 500 * 1024)
                            {
                                base.AlertMessageBack("图片大小不能超过500K");
                            }

                            string fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(Request.Files[0].FileName);
                            Request.Files[0].SaveAs(MapPath("/UploadImages/RiseBaby/" + fileName));
                            fileImageBig = "/UploadImages/RiseBaby/" + fileName;
                            sdata.BabyImage = fileImageBig;
                        }
                        catch (Exception ex)
                        {
                            base.AlertMessageBack("保存失败：" + ex.Message);
                            // context.Response.Write( "上传文件失败" );
                        }
                    }
                    else
                    {
                        sdata.BabyImage = Convert.ToString(dbHelper.FilterSql(Request.Form["ModBabyImage"].Trim()) ?? "");
                    }



					sdata.OrderId  = Convert.ToInt32(dbHelper.FilterSql(Request.Form["ModOrderId"].Trim())?? "");
					sdata.ExInt  = Convert.ToInt32(dbHelper.FilterSql(Request.Form["ModExInt"].Trim())?? "");
					sdata.ExString  = Convert.ToString(dbHelper.FilterSql(Request.Form["ModExString"].Trim())?? "");
				var id = sdata.Id;
				if (id == 0)
				{
					//增加
					if (InsertData(sdata))
					{
						Response.Redirect(redirectUrl);
						Response.End();
					}
					else
					{
						Response.Write("error");
						Response.End();
					}
				}
				else
				{
					//修改
					if (UpdateData(sdata))
					{
						Response.Redirect(redirectUrl);
						Response.End();
					}
					else
					{
						Response.Write("error");
						Response.End();
					}
				}
			}
		}
		#endregion
		
		
		#region 增删改
		
		/// <summary>
		/// 添加数据
		/// </summary>
		/// <param name="sdata"></param>
		/// <returns></returns>
		private bool InsertData(RiseBaby sdata)
		{
			string sqlStr = @"INSERT INTO RiseBaby(
					[BabyName],
							[BabyUrl],
							[BabyImage],
							[OrderId],
							[ExInt],
							[ExString]	)VALUES(
					@BabyName,
							@BabyUrl,
							@BabyImage,
							@OrderId,
							@ExInt,
							@ExString)";
			SqlParameter[] parms = new SqlParameter[] {
					new SqlParameter("@BabyName",sdata.BabyName),
							new SqlParameter("@BabyUrl",sdata.BabyUrl),
							new SqlParameter("@BabyImage",sdata.BabyImage),
							new SqlParameter("@OrderId",sdata.OrderId),
							new SqlParameter("@ExInt",sdata.ExInt),
							new SqlParameter("@ExString",sdata.ExString)};
			int ret = db.GetExecuteNonQuery(null, sqlStr, parms);
			return ret > 0;
		}
		
		
		/// <summary>
		/// 修改数据
		/// </summary>		
		/// <param name="sdata"></param>
		/// <returns></returns>
		private bool UpdateData(RiseBaby sdata)
		{
			string sqlStr = @"UPDATE RiseBaby SET
					[BabyName]=@BabyName,
										[BabyUrl]=@BabyUrl,
										[BabyImage]=@BabyImage,
										[OrderId]=@OrderId,
										[ExInt]=@ExInt,
										[ExString]=@ExString WHERE Id=@Id";
				
				SqlParameter[] parms = new SqlParameter[] {
					new SqlParameter("@Id",sdata.Id),
										new SqlParameter("@BabyName",sdata.BabyName),
										new SqlParameter("@BabyUrl",sdata.BabyUrl),
										new SqlParameter("@BabyImage",sdata.BabyImage),
										new SqlParameter("@OrderId",sdata.OrderId),
										new SqlParameter("@ExInt",sdata.ExInt),
										new SqlParameter("@ExString",sdata.ExString)};
			int ret = db.GetExecuteNonQuery(null, sqlStr, parms);
			return ret > 0;
		}
		
		
		/// <summary>
		///单个删除
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		private bool DeleteData(long id)
		{
			string sqlStr = string.Format("DELETE FROM RiseBaby WHERE Id={0}",id);
			
			int ret = db.GetExecuteNonQuery(null, sqlStr, null);
			return ret > 0;
		}
		/// <summary>
		/// 批量删除
		/// </summary>
		/// <param name="idStr"></param>
		/// <returns></returns>
		private bool DeleteBatchData(string idStr)
		{
			string sqlStr = string.Format("DELETE FROM RiseBaby WHERE Id IN ({0})",idStr);
	
			int ret = db.GetExecuteNonQuery(null, sqlStr, null);
			return ret > 0;
		}
		
		
		/// <summary>
		/// 状态操作
		/// </summary>
		/// <param name="optype"></param>
		/// <param name="idStr"></param>
		/// <returns></returns>
		private bool SwitchBatchData(int optype,string idStr)
		{
			string sqlStr = "";
			if(optype==0)
				sqlStr = string.Format("UPDATE RiseBaby SET [Status]=0 WHERE Id IN ({0})",idStr);
			else
				sqlStr = string.Format("UPDATE RiseBaby SET [Status]=1 WHERE Id IN ({0})", idStr);
			
			int ret = db.GetExecuteNonQuery(null, sqlStr, null);
			return ret > 0;
		}
		

		
		#endregion
	}
}


